import React, { Component } from "react";
// import Link from 'umi/link';
import { PageHeaderWrapper } from "@ant-design/pro-layout";
import { connect } from "dva";
import styles from "./index.less";
import CreateForm from "./components/CreateForm";
import { pagination } from "@/utils/utils";
import UploadFiles from "@/components/UploadFiles";
import router from "umi/router";
import {
  Row,
  Col,
  Card,
  Select,
  Button,
  Table,
  Form,
  message,
  Popconfirm,
  Modal,
} from "antd";

@connect(({ jobManage }) => ({
  fakeCaptcha: jobManage.fakeCaptcha,
}))
class User extends Component {
  constructor(props) {
    super(props);
    this.state = {
      recvParam: this.props.location.state,
      createModalVisible: false,
      checkModalVisible: false,
      taskDescription: null,
      setPagination: {
        ...pagination,
      },
      searchRequest: {
        auditing: "",
        search: "",
      },
    };
    this.columns = [
      {
        title: "承揽方姓名",
        dataIndex: "userDetailResponse.name",
        align: "center",
      },
      {
        title: "联系方式",
        dataIndex: "userDetailResponse.mobile",
        align: "center",
      },
      {
        title: "邮箱",
        dataIndex: "userDetailResponse.emailAddress",
        align: "center",
      },
      {
        title: "服务进度",
        dataIndex: "userJobStatusDesc",
        align: "center",
      },
      {
        title: "操作",
        align: "center",
        render: (text, record, index) => (
          <span className={styles.operation}>
            <a
              onClick={() => {
                router.push({
                  pathname: "/taskManagement/userManage/jobReport",
                  state: {
                    userJobId: record.userJobId,
                    name: record.userDetailResponse.name,
                    userJobStatus: record.userJobStatus,
                  },
                });
              }}
            >
              进度汇报
            </a>
            <Popconfirm
              title={`确认删除承揽方“${record.userDetailResponse.name}”？`}
              onConfirm={async () => {
                await this.handleRemove(record.userJobId, index);
                // action.reload();
              }}
              // onCancel={cancel}
              okText="确定"
              cancelText="取消"
            >
              <a href="#">删除</a>
            </Popconfirm>
          </span>
        ),
      },
    ];
  }

  componentWillMount() {
    this.saveUserManageState();
  }

  componentDidMount() {
    this.getlistUserJob();
  }

  saveUserManageState = () => {
    const { state } = this.props.location;
    if (state) {
      //判断当前有参数
      sessionStorage.setItem("userManageState", JSON.stringify(state)); // 存入到sessionStorage中
    } else {
      const recvParam = JSON.parse(sessionStorage.getItem("userManageState")); // 当state没有参数时，取sessionStorage中的参数
      this.setState({
        recvParam,
      });
    }
  };

  getlistUserJob = () => {
    const { setPagination, recvParam } = this.state;
    const requestParams = {
      page: setPagination.current,
      size: setPagination.pageSize,
      jobId: recvParam.jobId,
    };
    this.props.dispatch({
      type: "jobManage/getlistUserJob",
      payload: requestParams,
    });
  };

  handleCheck = (flag, selectedRows = {}) => {
    this.setState({
      checkModalVisible: flag,
      taskDescription: selectedRows.taskDescription,
    });
  };

  handleCreatModalVisible = (flag) => {
    this.setState({ createModalVisible: flag });
  };

  refreshTable = async () => {
    window.location.reload("/");
  };

  /**
   * 添加节点
   * @param fields
   */
  handleAdd = async (fields) => {
    const { recvParam } = this.state;
    const hide = message.loading("正在添加");
    const requestParams = {
      jobId: recvParam.jobId,
      ...fields,
    };
    try {
      await this.props.dispatch({
        type: "jobManage/addUserJob",
        payload: requestParams,
      });
      hide();
      message.success("添加成功");
      this.getlistUserJob();
      this.handleCreatModalVisible(false);
      return true;
    } catch (error) {
      hide();
      message.error("添加失败请重试！");
      return false;
    }
  };

  handleRemove = async (userJobId, index) => {
    const hide = message.loading("正在删除");
    if (!userJobId) return true;
    try {
      await this.props.dispatch({
        type: "jobManage/deleteUserJob",
        payload: { userJobId, index },
      });
      hide();
      message.success("删除成功，即将刷新");
      return true;
    } catch (error) {
      hide();
      message.error("删除失败，请重试");
      return false;
    }
  };

  // 页码切换
  handlePageChange = async (current) => {
    const { setPagination } = this.state;
    await this.setState({
      setPagination: {
        ...setPagination,
        current,
      },
    });
    this.getlistUserJob();
  };

  // 每页/条 切换
  handleSizeChange = async (current, pageSize) => {
    const { setPagination } = this.state;
    await this.setState({
      setPagination: {
        ...setPagination,
        current,
        pageSize,
      },
    });
    this.getlistUserJob();
  };

  render() {
    const { fakeCaptcha } = this.props;
    const {
      recvParam,
      createModalVisible,
      setPagination,
      checkModalVisible,
      taskDescription,
    } = this.state;

    const pagination = {
      ...setPagination,
      total: fakeCaptcha.totalElements,
      showTotal: (count) => `总共 ${count} 条`,
      onShowSizeChange: this.handleSizeChange,
      onChange: this.handlePageChange,
    };
    return (
      <PageHeaderWrapper className={styles.userContainer}>
        <Button
          type="link"
          icon="step-backward"
          onClick={this.refreshTable}
          style={{ marginBottom: 4 }}
          onClick={() => router.push("/taskManagement")}
        >
          返回
        </Button>
        <Card bordered={false} className="marginB24">
          <Row type="flex" justify="space-between">
            <Col>{recvParam.title}</Col>
            <Col>
              <Button type="link" icon="redo" onClick={this.refreshTable}>
                刷新
              </Button>
              {/* <Link to='/taskManagement/userManage'>刷新</Link> */}
            </Col>
          </Row>
        </Card>

        <div className="wrapperClass">
          <Row type="flex" justify="space-between" className={styles.title}>
            <Col>承揽方：</Col>
            <Col>
              <UploadFiles
                url="/zb-job/import-job-user"
                downloadUrl="https://qiniu.jingyunhrs.com/FlaPTlMNxdqH6Q37IP6OGwOscTJt.xlsx"
                name="人员"
                refreshTable={this.getlistUserJob}
                jobId={recvParam.jobId}
              />
              <Button
                type="primary"
                icon="plus"
                onClick={() => this.handleCreatModalVisible(true)}
              >
                添加承揽方
              </Button>
            </Col>
          </Row>
          <Table
            rowKey="userJobId"
            columns={this.columns}
            dataSource={fakeCaptcha.content}
            pagination={pagination}
          />
        </div>

        <Modal
          destroyOnClose
          title="任务描述"
          visible={checkModalVisible}
          onCancel={() => this.handleCheck(false)}
          footer={[
            <Button
              key="submit"
              type="primary"
              onClick={() => this.handleCheck(false)}
            >
              关闭
            </Button>,
          ]}
        >
          <p>{taskDescription}</p>
        </Modal>

        <CreateForm
          onSubmit={(value) => this.handleAdd(value)}
          onCancel={() => this.handleCreatModalVisible(false)}
          modalVisible={createModalVisible}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Form.create()(User);
